package org.digitarts.rtms.spring.collectors.shell.local;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.Map;

import org.digitarts.rtms.spring.collectors.shell.IShell;

public class LocalWindowsShell implements IShell
{
	protected String[]	environment				= null;
	protected String	currentDirectory		= null;
	protected int		bufferSize				= 2048;
	protected File		currentDirectoryFile	= null;

	public LocalWindowsShell(String currentDirectory, int bufferSize)
	{
		this();
		this.currentDirectory = currentDirectory;
		currentDirectoryFile = new File(currentDirectory);
		this.bufferSize = bufferSize;
	}

	public LocalWindowsShell()
	{
		Map<?, ?> env = System.getenv();
		environment = new String[env.size()];
		int e = 0;
		for (Object name : env.keySet())
		{
			environment[e] = name.toString() + "=" + env.get(name).toString();
			e++;
		}
	}

	public String issueOSCommand(String command, Map<String, ?>... context) throws Exception
	{
		return issueOSCommand(command, 0, context);
	}

	public String issueOSCommand(String command, long timeOut, Map<String, ?>... context) throws Exception
	{
		StringBuilder buff = new StringBuilder();
		InputStream reader = null;
		try
		{
			Process p = Runtime.getRuntime().exec(command, environment, currentDirectoryFile);
			reader = new BufferedInputStream(p.getInputStream());
			byte[] buffer = new byte[bufferSize];
			int c = -1;
			while(0 <= (c = reader.read(buffer)))
			{
				buff.append(new String(buffer, 0, c));
			}
			return buff.toString();
		}
		catch (Throwable t)
		{
			return null;
		}
		finally
		{
			try
			{
				reader.close();
			}
			catch (Exception e)
			{
			}
		}
	}

	public String getCurrentDirectory()
	{
		return currentDirectory;
	}

	public void setCurrentDirectory(String currentDirectory)
	{
		this.currentDirectory = currentDirectory;
	}

	public int getBufferSize()
	{
		return bufferSize;
	}

	public void setBufferSize(int bufferSize)
	{
		this.bufferSize = bufferSize;
	}

}
